let myApp = {
	data: function() {
		return {
			flag: false, //上升，下降
			selKey: "persent", //排序關鍵字
			szTotal: 0, //深证总数
			shTotal: 0, //上证总数
			todayTotal: 0, //单日盈亏
			totalSum: 0, //总盈亏
		}
	},
	methods: {
		openK(item) {
			window.open("chart.html?code=" + item.code + "&name=" + item.name, item.name,
				'top=10,left=10,width=1024,height=500');
			window.open("prop.html?code=" + item.code + "&name=" + item.name, item.name,
				'top=10,left=10,width=1024,height=500');
		},
		openDell(item) {
			window.open("buySell.html?code=" + item.name, item.name, 'top=10,left=10,width=1024,height=500');
		},
		switchUpDown() {
			this.flag = !this.flag;
		},
		checkIsDown(arr) {
			let work = "";
			
			arr.map(res => {
				work += res.isDown ? res.name + "到達買入價," : "";
			});
			if (work != "") {
				this.speak(work);
			}

		},
		//算出现在持有合计
		calTotal() {

			if (this.group[this.key] && this.group[this.key].key.indexOf("现在持有")==-1) return;
			let that = this;
			that.szTotal = that.shTotal = that.todayTotal = that.totalSum = 0;
			let str = "";
			let day = new Date().Format("yyyy-MM-dd");
			this.list.map(item => {
				if (item.days && item.days.length > 0) {
					let yesDay = parseFloat(this.getDataByDate(item.days, day)[2]);

					item.nowTotal = ((item.price - yesDay) * item.stkqty).toFixed(2);
					that.todayTotal += parseFloat(item.nowTotal);

					item.totalSum = ((item.price - item.cost) * item.stkqty).toFixed(2);
					that.totalSum += parseFloat(item.totalSum);

					str += parseFloat(item.nowTotal) + "+"
				}

				if (item.code.indexOf("sz") != -1) {
					that.szTotal += 1;
				} else {
					that.shTotal += 1;
				}
			});

			that.totalSum = that.totalSum.toFixed(2);
			that.todayTotal = that.todayTotal.toFixed(2);
		},
		getDataByDate(arr, today) {
			for (let i = 0; i < arr.length; i++) {
				if (arr[i][0] == today) {
					return arr[i + 1];
				}
			}
			return arr[0];
		},
		//今日总盈亏
		makeTodaySum() {
			if (this.group[this.key].key.indexOf("现在持有")==-1) return;
			let todaySum = this.todayTotal > 0 ? "欧夜，今天盈利" + this.todayTotal + "元" : "撸柒拉，今日亏损失：" + this.todayTotal + "元";
			this.speak(todaySum);
		},
		//找出超出當日漲跌3%的股票
		speak3Persent(){
			if (this.group[this.key].key.indexOf("现在持有")==-1) return;
			let work = "";
			this.list.map(item => {
				if (item.isOpen && item.upDownFlag) {
					work += item.persent >= 3 ? item.name + "上升" + item.persent : '';
					work += item.persent <= -3 ? item.name + "下跌" + item.persent : '';
				}
			});
			return work;


		},
		//突破最大最小值
		speakUpDown(){
			if (this.group[this.key].key.indexOf("现在持有")==-1) return;
			let work = "";
			this.list.map(item => {

				if (item.isOpen && item.isUp) {
					work += item.name + "突破" + item.up;
				}
				if (item.isOpen && item.isDown) {
					work += item.name + "跌破" + item.down;
				}

			});
			return work;
		},
		//翻红翻绿
		speakRedGreen(){
			if (this.group[this.key].key.indexOf("现在持有")==-1) return;
			let work = "";
			this.list.map(item => {

				if (item.redFlag && item.realPrice>50) {
					work += item.name + "翻红可出货,";
				}

				if (item.greenFlag && item.realPrice <= 0) {
					work += item.name + "翻綠了,";
				}

			});
			return work;
		},
		//最高，最低值
		speakBuySell(){
			if (this.key== "sh" || this.key == "sz" || this.group[this.key].key.indexOf("现在持有")==-1) return;
			let work = "";
			this.list.map(item => {

				let isPowerUp = this.isPowerUp(item);//放量

				if(item.price==item.nowData.maxPrice && isPowerUp && item.persent>2){
					work+=item.name+"放量新高";
				}
				if(item.price==item.nowData.minPrice && isPowerUp && item.persent<-1){
					work+=item.name+"放量新低";
				}

			});
			return work;
		},

		isPowerUp(item){
			let arr = [];

			let allPower = 0;
			let powerIdx = 0;
			for(let i = 0;i<item.dateList.length;i++){
				let dateP =parseInt(item.dateList[i].split(" ")[2]);
				let avg = dateP/(i+1)*2;
				if(i>0){
					let datePre = parseInt(item.dateList[i-1].split(" ")[2]);
					let nowDeal = dateP-datePre;
					if(nowDeal>avg){
						arr.push(item.dateList[i]);
						powerIdx = i;
					}
				}

			}
			return powerIdx+2>item.dateList.length;



		},
		//閲讀文字
		speak(work) {

			let utterance = new SpeechSynthesisUtterance();
			utterance.text = work;
			utterance.volume = 100;
			window.speechSynthesis.speak(utterance)
		},
		//添加分組
		addGroup: function() {
			var btnArray = ['取消', '确定'];
			mui.prompt('请输入分组名称：', '输入分组', '提示', btnArray, function(e) {
				if (e.index == 1) {

					this.app.group.push({key:e.value,list:[]});

				}
			})
		},
		//排序
		sortBy(arr, key, sortFlag) {
			arr.sort((a, b) => {
				return sortFlag ? a[key] - b[key] : b[key] - a[key];
			});
		},
		sortBy2(arr, key) {
			arr.sort((a, b) => {
				return a[key];
			});
		},

		showList() {
			if(this.key=="sz" || this.key=="sh"){
				var start = (this.curPage-1)*20;
				var end = start+20;
				this.list = this.key=="sh"?sh.slice(start,end):sz.slice(start,end);
			}else{
				this.list = this.group[this.key].list;
			}


			this.list.map(item=>{
				item.days=null;
				cul(item.code);
			});
			this.getPrices();
			this.calTotal();
		
		},
		culBuySell(result){
			this.list.map(item=>{
				if(item.code == result.code){
                    item.now=result.now;//当年数据
					item.pre=result.pre;//上年数据
					item.buyScore=result.buy.toFixed(2);//买入指数分
					item.sellScore=result.sell.toFixed(2);//卖出指数分
					item.max=result.max;
					item.min=result.min;
					item.down=item.now.min>item.pre.min?item.now.min:item.pre.min;
					item.up = item.now.max<item.pre.max?item.now.max:item.pre.max;
					// item.buySell=result;
				}
			});
		},
		vibrate() {
			if (this.isVibrate) return;
			let that = this;
			console.log("vibrating!!!!!");
			//plus.device.vibrate(2000);
			//plus.device.beep(2);
			setTimeout(() => {
				that.isVibrate = false;
			}, 2000)
		},
		goDetail(code) {
			let path1 = "https://emwap.eastmoney.com/quote/stock/";
			if (code.indexOf("sz")) {
				path1 += "1." + code.substr(2, 6) + ".html"
			} else {
				path1 += "0." + code.substr(2, 6) + ".html"
			}
			this.path = path1;

			window.open(path1, code, 'top=10,left=10,width=375,height=600');
			//this.isPath = true;
		},
		openDoctor(code) {
			let path = "https://m.10jqka.com.cn/doctor/" + code.substr(2, 6) + "/";
			let path2 = "https://bdstatics.eastmoney.com/web/prd/cwtj/index.html#/company?code=" + code.substr(2, 6);
			window.open(path, '分析', 'top=10,left=10,width=375,height=600');
			window.open(path2, '分析2', 'top=10,left=400,width=375,height=600');

		},
		setOpen(item) {
			item.isOpen = !item.isOpen;
			item.isDown = item.isUp = false;
			this.$forceUpdate();
			this.group[this.key].list = this.list;
			localStorage.setItem("group", JSON.stringify(this.group));

		},
		
		makeInfo(row){
			let code = row.code.substr(2,6);
			if(row.buyFlag){
				this.info+="B:"+code+","+row.stkqNum+";"
			}
			if(row.sellFlag){
				this.info+="S:"+code+","+row.stkqNum+";";
			}
		},
		drawLine(row){
			let xData = [];
			let yData  =[];
			let powerArr = [];

			let yesterdayPrice = row.nowData.yesterdayPrice;
			for(let i = 0;i<row.dateList.length;i++){
				let item = row.dateList[i];
				let arr = item.split(" ");
				xData.push(arr[0]);
				yData.push(parseFloat(arr[1]));

				if(i>0){
					let p = arr[2] - row.dateList[i-1].split(" ")[2];
					powerArr .push(p/10000);
				}
			}
			row.powerArrs = powerArr;
			if(row.code.indexOf("600111")!=-1){
				//this.isPowerUp(row);
			}
			let option = {

				tooltip: {
					trigger: 'axis'
				},
				xAxis: {
					type: 'category',
					data: xData,
				},
				yAxis:{
					scale:true,
					min: (value) => {
						return value.min*0.99;
					},
					max: (value) => {
						return value.max*1.01;
					}
				},
				series: [
					{
						markLine:{
							data:[{yAxis:yesterdayPrice},{yAxis:row.halfBuyCost},{yAxis:row.halfSellCost}]
						},
						data: yData,
						type: 'line'
					}
				]
			};

			//let chart=echarts.init(document.getElementById(row.code));
			//chart.setOption(option);
		},
		getPrices() {
			//获取和计算属性
			this.list.forEach(row=>{
				row.day=this.day;
			});
			MakeDataHandel.getData(this.list,()=>{
				this.sortBy(this.list, this.selKey, this.flag);
				//this.sortBy(this.list, 'keeping', this.flag);
					this.$forceUpdate();
					this.info="";
					this.list.forEach(row=>{
						this.drawLine(row);
						this.makeInfo(row);
					})
				});
				
			
		},
	
		culAllFee() {
			if (this.editItem.bitList.length == 0 || !this.editItem.bitList) {
				this.editItem.bitList = [];
				this.editItem.buyCost = this.editItem.sellCost = this.editItem.num = 0;
				return;
			}
			//买卖手续费
			let arr = this.editItem.bitList;
			let item = arr[arr.length - 1];
			let sellCost = item.num * item.price * 0.001 + 5; //卖出的成本=印花税（总成交金额的千份之一）+5元左右过户费；
			let buyCost = 5; //买入成本;
			this.editItem.num = item.num;
			if (item.type == "0") {
				//买入所需成本
				this.editItem.buyCost = ((sellCost + buyCost) / item.num + parseFloat(item.price)).toFixed(3);
			} else {
				//卖出所需成本
				this.editItem.sellCost = sellCost;
			}

		},
		saveBit() {

			this.culAllFee();
			this.saveInList();
			this.isBuySell = false;
			this.closeSwipe()
			this.group[this.key] = this.list;
			localStorage.setItem("group", JSON.stringify(this.group));
		},

		saveInList() {
			try {
				this.list.forEach(item => {
					if (item.code == this.editItem.code) {
						item.buyCost = this.editItem.buyCost;
						item.sellCost = this.editItem.sellCost;
						item.bitNum = this.editItem.num;
						item.bitList = this.editItem.bitList;
						throw Error();
					}
				})
			} catch (e) {}
		},
		setting(item, idx) {

			this.editItem = JSON.parse(JSON.stringify(item));
			this.editItem.isAdd = false;
			this.editItem.idx = idx;
			this.isEdit = true;
		},
		add() {
			this.editItem = {
				isAdd: true
			}
			this.isEdit = true;
		},
		//保存数据，固化
		save(){
			let data = "let groupData="+JSON.stringify(this.group);
			saveAs(data,"groupData.js","text/plain;charset=utf-8");
			localStorage.setItem("group", JSON.stringify(this.group));

		},
		//0，修改增加单个股票，1-批量添加持有股票网页版复制出来json数据，2，批量增加股票数据库复制出来
		saveTempData() {
			let myList = [];
			switch(this.type){
				case "0":
					this.editItem.up = this.editItem.up ? parseFloat(this.editItem.up) : null;
					this.editItem.down = this.editItem.down ? parseFloat(this.editItem.down) : null;
					this.editItem.cost = this.editItem.cost ? parseFloat(this.editItem.cost) : null;
					this.editItem.stkqty = this.editItem.stkqty?this.editItem.stkqty:null;
					this.editItem.stkqNum = this.editItem.stkqNum?this.editItem.stkqNum:null;
					if (this.editItem.isAdd) {
						this.list.unshift(this.editItem);
					} else {
						this.list[this.editItem.idx] = this.editItem;
						this.closeSwipe()
					}
					this.group[this.key].list = this.list;

					break;
				case "1":
					myList = JSON.parse(this.editItem.list).result;
					myList.map(item => {
						item.code = item.market == "0" ? "sz" : "sh";
						item.code = item.code + item.stkcode;
						item.cost = item.profitprice;
						item.isOpen = true;
						item.redFlag = true;
						item.upDownFlag = true;
						this.group[this.key].list.map(item2 => {
							if (item2.code == item.code) {
								item.up = item2.up;
								item.down = item2.down;
								item.isOpen = item2.isOpen;
								item.upDownFlag = item2.upDownFlag;
								item.redFlag = item2.redFlag;
								item.greenFlag = item2.greenFlag;
								item.bitList = item2.bitList;
								item.buyCost = item2.buyCost;
								item.sellCost = item2.sellCost;
								item.bitNum = item2.bitNum;
							}

						});

					});

					this.group[this.key].list = myList;
					this.list = myList;
					break;
				case "2":
					myList=[];
					this.editItem.list.split(" ").map(item => {
						if (item.length > 10) {
							let node = {};

							let code = item.split("\t")[2];
							if (code.substr(0, 1) == "6") {
								node.code = "sh" + code;
							} else {
								node.code = "sz" + code;
							}
							node.cost = parseFloat(item.split("\t")[3]);
							myList.push(node);
						}
					});
					this.group[this.key].list = this.group[this.key].list.concat(myList);
					this.list = this.group[this.key].list;
					break;
			}
			this.isEdit = false;
		},
		saveMenu(){
			let sortIdx = document.getElementsByClassName("menuIdx");
			let newGroup = [];
			for(let i = 0;i<sortIdx.length;i++){
				newGroup[sortIdx[i].value] = this.group[i];
			}
			let data = "let groupData="+JSON.stringify(newGroup);
			saveAs(data,"groupData.js","text/plain;charset=utf-8");
			localStorage.setItem("group", JSON.stringify(newGroup));
		},

		//移动选中的股票到某个组
		move(){
			this.selItem=[];
			mui(".myRows").each(item=>{
				if(mui(".myRows")[item].checked){
					this.selItem.push(this.list[mui(".myRows")[item].id]);
				}

			});

			this.isAddGu = true;
		},
		setKey(e){
			this.key = e;
			this.showList();
			this.$forceUpdate();
		},
		saveGu(){
			this.group[this.key].list = this.group[this.key].list.concat(this.selItem);
			this.isAddGu = false;
		},
		del(idx) {
			let that = this;
			var btnArray = ['确认', '取消'];
			mui.confirm('你确认删除该条记录？', '删除', btnArray, function(e) {
				if (e.index == 0) {
				debugger;
					that.list.splice(idx, 1);
					that.group[that.key].list = that.list;

					localStorage.setItem("group", JSON.stringify(that.group));


				} else {
					that.closeSwipe()
				}
			});
		},
		closeSwipe() {
			let idx = 0;
			this.list.map(item => {
				let node = document.getElementById("li" + idx);
				mui.swipeoutClose(node);
				idx++;


			})
		},
		sell(item) {

			var d = new Date().Format("yyyyMMdd");
			var path = "https://trade2.guosen.com.cn/trade/views/index.html?v=" + d + "#/stk/sell?code=" + item.stkcode +
				"&secuid=" + item.secuid;
			window.open(path, d+item.name, 'top=10,left=10,width=1024,height=500');
		},
		buy(item) {
			var d = new Date().Format("yyyyMMdd");
			var path = "https://trade2.guosen.com.cn/trade/views/index.html?v=" + d + "#/stk/buy?code=" + item.stkcode
			window.open(path, d+item.name, 'top=10,left=10,width=1024,height=500');
		},
		
		getListByKey(key,callBack){
			//通过键值获取股票列表
			this.group.forEach(item=>{
				if(item.key == key)
				{
					console.log(key)
					callBack(item);
					return item;
				}
			})
		},

	}
};
